package com.lcq.study.test.demo;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

/**
 * @ClassName AccessTokenUtils
 * @Description
 * @Author lichuanqi
 * @Date 2023/2/14 11:26
 * @Version 1.0
 **/
public class AccessTokenUtils {
    private AccessTokenUtils() {
    }

    public static final String SPLIT = ":";
    //超时时间，秒
    public static final long EXPIRE_TIME = 86400L;

    public static String createToken(String appKey, String aesKey) {
        String content = appKey + SPLIT + System.currentTimeMillis();
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, HexUtil.decodeHex(aesKey));
        return aes.encryptHex(content);
    }


    public static String decryptToken(String token, String aesKey) {
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, HexUtil.decodeHex(aesKey));
        return aes.decryptStr(token);
    }

    public static void test() {
        String content = "YmltLXl1ZXhpdS0yMDIz";
        String keyStr = "42272a3b868cdb7a9c8d2a24d93daf08";
        //构建
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, HexUtil.decodeHex(keyStr));

        //加密为16进制表示
        String encryptHex = aes.encryptHex(content);

        System.out.println(encryptHex);

        //解密为字符串
        String decryptStr = aes.decryptStr(encryptHex);

        System.out.println(decryptStr);
    }

/*    public static void main(String[] args) {


        String content = "YmltLXl1ZXhpdS0yMDIz:1694495439932";
        String keyStr = "42272a3b868cdb7a9c8d2a24d93daf08";
        //构建
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, HexUtil.decodeHex(keyStr));

        //加密为16进制表示
        String encryptHex = aes.encryptHex(content);

        System.out.println(encryptHex);

        //解密为字符串
        String decryptStr = aes.decryptStr(encryptHex);

        System.out.println(decryptStr);
    }*/

    public static String generateKey() {
        //随机生成密钥
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        return HexUtil.encodeHexStr(key, true);
    }
}
